package com.framework.loippi.controller.order;

import com.framework.loippi.controller.GenericController;
import com.framework.loippi.entity.TOrder;
import com.framework.loippi.service.TOrderService;
import com.framework.loippi.support.Message;
import com.framework.loippi.support.Pageable;
import com.framework.loippi.utils.ParameterUtils;
import com.framework.loippi.utils.StringUtil;
import com.framework.loippi.utils.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller - 订单管理
 *
 * @author wmj
 * @version 2.0
 */
@Controller("adminTOrderController")
@RequestMapping({"/admin/order"})
public class TOrderController extends GenericController {

    @Resource
    private TOrderService tOrderService;

    /**
     * 跳转添加页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = {"/add"}, method = {RequestMethod.GET})
    public String add(ModelMap model) {
        return "/admin/order/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(TOrder tOrder, RedirectAttributes redirectAttributes) {
        tOrderService.save(tOrder);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Long id, ModelMap model) {
        TOrder tOrder = tOrderService.find(id);
        model.addAttribute("tOrder", tOrder);
        return "/admin/order/edit";
    }


    /**
     * 详情
     */
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public String view(@PathVariable Long id, ModelMap model) {
        TOrder tOrder = tOrderService.find(id);
        model.addAttribute("tOrder", tOrder);
        return "/admin/order/view";
    }


    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(TOrder tOrder, RedirectAttributes redirectAttributes) {
        tOrderService.update(tOrder);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 列表查询
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = {"/list"}, method = {RequestMethod.GET})
    public String list(Pageable pageable, HttpServletRequest request, ModelMap model) {

        Map<String, Object> paramter = ParameterUtils.getParametersMapStartingWith(request, "filter_");
        Map map = new HashMap();
        for (String key : paramter.keySet()) {
            if (!StringUtil.isEmpty(paramter.get(key).toString())) {
                map.put(key, paramter.get(key));
            }
        }
        String keyword = request.getParameter("keyword");
        String status = request.getParameter("statusKey");
        if (!StringUtils.isNullOrEmpty(keyword)) {
            map.put("userNamelike", keyword);
            map.put("phonelike", keyword);
            map.put("nicknamelike", keyword);
        }
        if (!StringUtils.isNullOrEmpty(status)) {
            map.put("orderStatus", status);
        }

        pageable.setParameter(map);
        model.addAttribute("paramter", paramter);
        model.addAttribute("page", this.tOrderService.findByPage(pageable));
        return "/admin/order/list";
    }

    /**
     * 删除操作
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST})
    public @ResponseBody
    Message delete(Long[] ids) {
        this.tOrderService.deleteAll(ids);
        return SUCCESS_MESSAGE;
    }

    // 导出Excel
    @RequestMapping(value = {"/outputExcel"}, method = {RequestMethod.GET})
    public @ResponseBody
    void outputExcel(HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HSSFWorkbook hw = new HSSFWorkbook();
        HSSFSheet hs = hw.createSheet("sheet0");
        String[] strings = {"订单姓名", "地址", "电话", "商品", "价格"};

        // 设置表头
        HSSFRow hr = hs.createRow(0);
        for (int i = 0; i < strings.length; i++) {
            HSSFCell hc = hr.createCell(i);
            hc.setCellValue(strings[i]);
        }
        List<TOrder> subjects = tOrderService.findToExcel();

        // 数据写入excel
        for (int i = 0; i < subjects.size(); i++) {
            // 从第一行开始写入
            HSSFRow hssfRow = hs.createRow(i + 1);
            if (subjects.get(i).getUserName() != null) {
                HSSFCell cell = hssfRow.createCell(0);
                cell.setCellValue(subjects.get(i).getUserName());
            }
            if (subjects.get(i).getAddressDetail() != null) {
                HSSFCell cell = hssfRow.createCell(1);
                cell.setCellValue(subjects.get(i).getAddressDetail());
            }
            if (subjects.get(i).getPhone() != null) {
                HSSFCell cell = hssfRow.createCell(2);
                cell.setCellValue(subjects.get(i).getPhone());
            }
            if (subjects.get(i).getItems() != null) {
                String str = "";
                for (int j = 0; j < subjects.get(i).getItems().size(); j++) {
                    str += subjects.get(i).getItems().get(j).getMedicineName() + ",";
                }
                HSSFCell cell = hssfRow.createCell(3);
                cell.setCellValue(str);
            }
            if (subjects.get(i).getAmount() != null) {
                HSSFCell cell = hssfRow.createCell(4);
                cell.setCellValue(String.valueOf(subjects.get(i).getAmount()));
            }
        }
        OutputStream out = null;
        // 导出的excel名称
        String fileName = "科目.xls";
        try {
            out = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            hw.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
